package com.woniu.springmybatis.action;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.deploy.net.HttpResponse;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.woniu.springmybatis.entity.*;
import com.woniu.springmybatis.service.*;
import com.woniu.springmybatis.tools.JsonUtil;
import jdk.nashorn.internal.runtime.JSONFunctions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/UserController")
public class UserController {
	@Resource
	private Vi_account_user_depatment_position_councilService vi_account_user_depatment_position_councilService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private CouncilService councilService;
	@Resource
	private PositionService positionService;
	@Resource
	private UserService userService;

	/*
	查询所有用户的基本信息（姓名、性别、）
	 */
	@RequestMapping("/showAllUsers.do")
	public String showAllUsers(Model model, HttpServletRequest httpServletRequest, @RequestParam(required = true, defaultValue = "1") Integer page,
							   @RequestParam(required = false, defaultValue = "8") Integer pageSize) {
		PageHelper.startPage(page, pageSize);
		// 调用方法得到所有用户的基本信息
		// 判断登录用户是否是超级管理员,超级管理员的account.id=1
		Account account = (Account) httpServletRequest.getSession().getAttribute("account");

		List<Vi_account_user_depatment_position_council> lists = this.vi_account_user_depatment_position_councilService.showAllUsers(account);
		PageInfo<Vi_account_user_depatment_position_council> p = new PageInfo<>(lists);
		// 将结果保存到request中
		model.addAttribute("userList", lists);
		model.addAttribute("page", p);
		return "userManage";
	}

	/*
	按照用户输入的条件查询用户基本信息
	 */
	@RequestMapping("/searchUser.do")
	public String searchUser(Model model, @RequestParam(required = true, defaultValue = "1") Integer page,
							 @RequestParam(required = false, defaultValue = "8") Integer pageSize, HttpServletRequest httpServletRequest) {
		// 获取用户输入的搜索关键字
		String searchText = httpServletRequest.getParameter("searchText");
		// 判断登录用户是否是超级管理员,超级管理员的account.id=1
		Account account = (Account) httpServletRequest.getSession().getAttribute("account");
		/*
		如果用户没有输入就点击查询，则应该显示所有用户的基本信息
		 */
		if (searchText.equals("")) {
			return "redirect:../UserController/showAllUsers.do";
		} else {
			// 开始分页
			PageHelper.startPage(page, pageSize);
			List<Vi_account_user_depatment_position_council> lists = this.vi_account_user_depatment_position_councilService.searchUser(searchText, account);
			PageInfo<Vi_account_user_depatment_position_council> p = new PageInfo<>(lists);
			model.addAttribute("userList", lists);
			model.addAttribute("page", p);
		}
		return "userManage";
	}

	/*
	显示具体用户的详细信息，进入展示和修改用户信息的JSP
	 */
	@RequestMapping("/showUserInfo.do")
	public String showUserInfo(Model model, HttpServletRequest httpServletRequest) {
		//获取操作用户选择的具体用户的id
		String uid = httpServletRequest.getParameter("u_id");
		List<Vi_account_user_depatment_position_council> lists = this.vi_account_user_depatment_position_councilService.showUserInfo(uid);
		// 将结果存储进request中
		model.addAttribute("userInfo", lists);
		HttpSession session = httpServletRequest.getSession();
		Account account = (Account) session.getAttribute("account");
		System.out.println(account);
		return "userInfo";
	}

	@RequestMapping("/changeUserStatus.do")
	public String changeUserStatus(HttpServletRequest httpServletRequest) {
		// 获取需要更新状态的用户id
		String uid = httpServletRequest.getParameter("uid");
		boolean flag = this.vi_account_user_depatment_position_councilService.changeUserStatus(uid);
		return "redirect:../UserController/showAllUsers.do";
	}

	/**
	 * 新增用户的准备工作-需要获得局级单位、职位列表
	 *
	 * @return
	 */
	@RequestMapping("/addNewUserPre.do")
	public String addNewUserPre(Model model) {
		// 得到局级单位列表
		List<Council> councilList = this.councilService.getCouncilList();
		// 得到职位列表
		List<Position> positionList = this.positionService.getPosList();
		model.addAttribute("councilList", councilList);
		model.addAttribute("positionList", positionList);
		return "addNewUser";
	}

	/**
	 * 新增用户：选择局级单位之后得到下属的部门列表，并通过JSON返回页面
	 *
	 * @return
	 */
	@RequestMapping("/getDepList.do")
	@ResponseBody
	public String getDepList(Model model, HttpServletRequest httpServletRequest) {
		String msg = "";
		try {
			// 得到页面上用户选择的局级单位的ID
			String councilId = httpServletRequest.getParameter("councilId");
			System.out.println("用户选择的局级单位id是：" + councilId);
			// 根据局级单位id得到下属部门的列表
			List<Department> lists = this.departmentService.getDepList(councilId);
			for (int i = 0; i < lists.size(); i++) {
				System.out.println(lists.get(i));
			}
			// 准备存储转换
			List<Map<String, String>> msgList = new ArrayList<Map<String, String>>();
			// 判断
			if (lists.size() > 0) {
				for (int i = 0; i < lists.size(); i++) {
					Department dep = lists.get(i);
					Map<String, String> msgMap = new HashMap<String, String>();
					msgMap.put("dep_id", dep.getId().toString());
					msgMap.put("dep_name", dep.getD_name());
					msgList.add(msgMap);
				}
				if (msgList.size() > 0) {
					System.out.println("===========msgList");
					for (int i = 0; i < msgList.size(); i++) {
						System.out.println(msgList.get(i));
					}
					msg = JsonUtil.listToJson(msgList);
					System.out.println("转换后");
					System.out.println(msg);
					/*msg = msg.substring(1,msg.length()-1);
					System.out.println("截取后："+msg);*/
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}

	@RequestMapping("/addNewUser.do")
	@ResponseBody
	/*
	新增用户
	存在问题：
	1-新增局长如何设置
	2-在已有部长的基础上新增部长如何设置

	！！！！修改了数据库表user！！！！

	返回不同的状态显示不同的新增结果：
	1-表示用户名重复
	2-表示用户名长度不合法
	3-表示登录密码长度不合法
	4-表示两次密码不一致
	5-写入account表失败（新增失败）
	6-写入user表失败
	7-新增成功
	 */
	public String addNewUser(HttpServletRequest httpServletRequest) {
		// 获取数据
		// 登录名
		String loginAccount = httpServletRequest.getParameter("loginAccount");
		// 登录密码
		String loginPass = httpServletRequest.getParameter("loginPass");
		// 确认登录密码
		String confirmLoginPass = httpServletRequest.getParameter("confirmLoginPass");
		// 用户新名
		String name = httpServletRequest.getParameter("name");
		// 用户所属局级单位id
		String council = httpServletRequest.getParameter("councilId");
		// 用户所属部门id
		String department = httpServletRequest.getParameter("departmentId");
		System.out.println("用户傻逼：局级单位长度+" + council.length() + "部门长度" + department.length());
		// 用户职位id
		/*String position = httpServletRequest.getParameter("positionId");*/
		/*// 将数据存储到数组中
		String content[] = {loginAccount,loginPass,confirmLoginPass,name,council,department,position};
		for (int i = 0; i < content.length; i++) {
			System.out.println(content[i]);
		}*/
		// 存到map中
		Map<String, String> map = new HashMap<String, String>();
		map.put("loginAccount", loginAccount);
		map.put("loginPass", loginPass);
		map.put("confirmLoginPass", confirmLoginPass);
		map.put("name", name);
		map.put("council", council);
		map.put("department", department);
		/*map.put("position", position);*/
		// 验证是否成功
		Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry<String, String> entry = entries.next();
			System.out.println("key=" + entry.getKey() + '\t' + "value=" + entry.getValue());
		}
		int result = this.userService.addNewUser(map);
		System.out.println("新增用户结果：" + result);
		/*
		 如果要弹窗的话是否只能使用AJAX？
		 弹窗之后点击确认如何跳转回显示所有用户的页面
		  */
		String msg = JsonUtil.numberToJson(result);
		return msg;
	}
}
